<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span v-if="code">编辑入库单</span>
          <span v-if="!code">新增入库单</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="together-content">
      <!-- 新增/编辑入库单的入库单信息 -->
      <div>
        <el-form :inline="true" label-width="auto" style="width: 100%">
          <!-- 调拨单编码：在后端生成，需要结合分布式锁，因为在并发环境下 -->
          <el-form-item label="单据编号" v-if="inboundOrder.code">
            {{ inboundOrder.code }}
          </el-form-item>

          <!-- 时间范围选择 -->
          <el-form-item label="日期">
            <el-date-picker v-model="datePickerValue" type="date" placeholder="选择日期" size="small" style="width: 150px"
              value-format="YYYY-MM-DD" @change="handleDateChange" />
          </el-form-item>

          <!-- 业务类别 -->
          <el-form-item label="业务：">
            <el-select style="width: 200px" v-model="inboundOrder.type">
              <el-option label="请选择" value="" />
              <el-option label="采购入库" :value="1" />
              <el-option label="退货入库" :value="2" />
              <el-option label="盘盈入库" :value="3" />
              <el-option label="调拨入库" :value="4" />
              <el-option label="其他入库" :value="0" />
            </el-select>
          </el-form-item><br /><br />

          <!--  -->
          <el-form-item label="关联源单">
            <el-input style="width: 150px" placeholder="选择源单" readonly v-model="inboundOrder.sourceOrderCode" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 分割线 -->
      <el-divider />

      <!-- 操作按钮 -->
      <div style="margin-bottom: 15px; text-align: right">
        <el-button type="primary" size="small" @click="save()" v-if="inboundOrder.status < 2">保存</el-button>
        <el-button type="success" size="small" @click="saveAndSubmit()" v-if="inboundOrder.status < 2">保存并提交</el-button>
        <el-button type="success" size="small" @click="auditor()" v-if="inboundOrder.status == 2">审核</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="inboundDetailList" style="width: 100%" border>
        <!-- 操作列 -->
        <el-table-column label="操作" width="80px" align="center" fixed="left" v-if="Number(inboundOrder.status) < 2">
          <template #default="scope">
            <!-- add -->
            <el-button link type="success" size="small" plain @click="addDetailRow(scope.$index)"><el-icon>
                <Plus />
              </el-icon></el-button>
            <!-- del -->
            <el-button link type="danger" size="small" plain @click="removeDetailRow(scope.$index)"><el-icon>
                <Minus />
              </el-icon></el-button>
          </template>
        </el-table-column>

        <!-- 商品 -->
        <el-table-column label="商品" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.goodsName" style="width: 95%" placeholder="选择商品"
              @click="openGoodsDialog(scope.row, scope.$index)" readonly />
          </template>
        </el-table-column>

        <!-- 商品类别 -->
        <el-table-column label="商品类别" width="150px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.categoryName" style="width: 95%" placeholder="商品类别" readonly />
          </template>
        </el-table-column>

        <!-- 规格 -->
        <el-table-column label="规格" width="150px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.specification" style="width: 95%" placeholder="规格" readonly />
          </template>
        </el-table-column>

        <!-- 采购单位 -->
        <el-table-column label="单位" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.unitId" style="width: 95%" :disabled="!scope.row.goodsId" @change="updateUnitName(scope.row)">
              <template v-if="scope.row.unitList">
                <el-option v-for="item in scope.row.unitList" :key="item.id" :label="item.name" :value="item.id" />
              </template>
            </el-select>
          </template>
        </el-table-column>

        <!-- 仓库 -->
        <el-table-column label="仓库" width="190px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.warehouseName" readonly placeholder="(所有)"
              @click="openWarehouseDialog(scope.row)" style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 可用库存 -->
        <el-table-column label="可用库存" width="150px" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.availableStock" style="width: 95%" placeholder="可用库存" readonly />
          </template>
        </el-table-column>

        <!-- 批次号（仅当 manageType === 1 时启用） -->
        <!--  <el-table-column v-if="showBatch" prop="batchNo" label="批次号" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.batchNo" @click="openBatchDialog(scope.row, scope.$index)"
              style="width: 95%" />
          </template>
        </el-table-column> -->
        <!-- 批次号（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch" prop="batchNo" label="批次号" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.batchNo" style="width: 95%" :readonly="scope.row.type != 1">
              <!-- 右侧图标：三个点（更多） -->
              <template #suffix>
                <el-icon @click.stop="openBatchDialog(scope.row, scope.$index)">
                  <MoreFilled />
                </el-icon>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 生产日期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch" prop="birthday" label="生产日期" width="180" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.birthday" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 有效期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch" prop="expiration" label="有效期(天)" width="110" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.expiration" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 入库数量 -->
        <!-- <el-table-column prop="quantity" label="数量" width="150" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.quantity" :step="1" style="width: 95%"
              @change="scope.row.totalPrice = scope.row.unitPrice * scope.row.quantity" />
          </template>
        </el-table-column> -->

        <!-- 入库数量 -->
        <el-table-column prop="quantity" label="数量" width="150" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.quantity" :step="1" :readonly="scope.row.type === 2" style="width: 95%;"
              @click="() => handleQuantityClick(scope.row, scope.$index)"
              @change="scope.row.totalPrice = scope.row.unitPrice * scope.row.quantity">
              <!-- 在输入框内部右侧显示 SN（仅 type === 2 时） -->
              <template #suffix>
                <span style="color: green; font-size: 12px;" v-if="scope.row.type == 2">SN</span>
              </template>
            </el-input>
          </template>
        </el-table-column>



        <!-- 入库单价 -->
        <el-table-column prop="unitPrice" label="入库单价" width="120" align="center">
          <template #default="scope">
            <el-input type="number" v-model.number="scope.row.unitPrice" style="width: 95%"
              @input="scope.row.totalPrice = scope.row.unitPrice * scope.row.quantity" />
          </template>
        </el-table-column>

        <!-- 入库金额（自动计算） -->
        <el-table-column prop="totalPrice" label="入库金额" width="120" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.totalPrice" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 库位 -->
        <el-table-column prop="warehouseLocationName" label="库位" width="180" align="center">
          <template #default="scope">
            <el-input readonly style="width: 95%" @click="openWarehouseLocationDialog(scope.row, scope.$index)"
              v-model="scope.row.warehouseLocationName" />
          </template>
        </el-table-column>


      </el-table><br />

      <!-- 调拨单备注 -->
      <el-input v-model="inboundOrder.remark" style="width: 100%" type="textarea" placeholder="暂无备注信息" />

      <!--操作日志-->
      <div style="margin-bottom: 15px; text-align: right">
        <br />
        <el-button plain @click="router.push({ name: 'inbound' })">历史记录</el-button>
        <el-button plain>操作日志</el-button>
      </div>

      <!-- 商品搜索列表弹出对话框 -->
      <FreeGoodsSelect ref="FreeGoodsRef" v-model="showSelectGoods" @confirm="handleSelectedGoods" />
      <!-- 批次号搜索列表弹出对话框 -->
      <el-dialog v-model="batchVisible" width="60%" style="height: auto;" draggable :show-close="true">
        <!-- 调用商品的搜索组件 -->
        <BatchListSelect v-model="batchVisible" @confirm="onBatchSelected" :goodsName="currentRow.goodsName"
          :goodsId="currentRow.goodsId">
        </BatchListSelect>
        <br /><br />
      </el-dialog>

      <!-- 仓库搜索列表弹出对话框 -->
      <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="60%" style="height: auto;" draggable
        :show-close="true">
        <!-- 调用仓库的搜索组件 -->
        <WareHouse ref="warehouseRef"
          :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
        <br /><br />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="warehouseVisible = false">取消</el-button>
            <el-button type="primary" @click="warehouseVisible = false">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 调用序列号的搜索组件 -->
      <el-dialog v-model="serialVisible" width="60%" style="height: auto;" draggable :show-close="true">
        <AddSerialNumber ref="AddSerialNumberRef" :goodsName="currentRow.goodsName" :list="currentRow.serialList"
          :status="inboundOrder.status">
        </AddSerialNumber>
        <br /><br />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="serialVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmSerialSelection">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 调用库位的搜索组件 -->
      <el-dialog v-model="warehouseLocationVisible" width="60%" style="height: auto;" draggable :show-close="true">
        <StorageLocation ref="warehouseLocationRef" :goodsName="currentRow.goodsName"></StorageLocation>
        <br /><br />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="warehouseLocationVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmStorageSelection">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>

      <div style="float: right; position: relative; top: -100px; left: -250px; z-index: 10;">
        <img src="@/assets/passed.png" width="120px" v-if="inboundOrder.status == 3" />
        <img src="@/assets/waitingpass.png" width="120px" v-if="inboundOrder.status == 2" />
        <img src="@/assets/passdefault.png" width="120px" v-if="inboundOrder.status == 0" />
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, watch, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCreatedDate, formatDate } from "@/util";
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import WareHouse from '@/views/basic/WareHouse.vue'
import AddSerialNumber from "./AddSerialNumber.vue";
import BatchListSelect from "./BatchListSelect.vue";
import StorageLocation from "@/views/basic/StorageLocation.vue";
let router = useRouter();
let axios = inject("axios");
// 仅用于绑定 el-date-picker 的日期部分（YYYY-MM-DD）
const datePickerValue = ref(null)
let inboundOrder = ref({
  createdTime: null,
  type: '',
  sourceOrderCode: '',
  status: 1, //1：已创建
  remark: '',
});

function handleDateChange(newDateStr) {
  // newDateStr 是 YYYY-MM-DD 字符串 或 null
  inboundOrder.value.createdTime = newDateStr ? formatCreatedDate(newDateStr) : null
}

//当前选中行
let currentRow = ref(null), currentIndex = ref(null);
//是否需要展示批次相关信息
let showBatch = ref(false);
let inboundDetailList = ref([]);

//仓库搜索选中结果
let warehouseVisible = ref(false)
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
  if (!newVisible) {
    if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
      console.log("selectedWarehouse", warehouseRef.value.selectedArray[0]);
      currentRow.value.warehouseName = warehouseRef.value.selectedArray[0].name //只选择一个，默认第一个
      currentRow.value.warehouseId = warehouseRef.value.selectedArray[0].id //只选择一个，默认第一个
      //获取到仓库编码，存数据库用，仓库name仅用作展示
      //用完之后清空，避免污染其他地方数据
      warehouseRef.value.clearSelected();
    }
  }
})



let batchVisible = ref(false);

const props = defineProps(["id"]);

function openWarehouseDialog(row) {
  warehouseVisible.value = true,
    currentRow.value = row;
}

let warehouseLocationVisible = ref(false);
function openWarehouseLocationDialog(row, index) {
  warehouseLocationVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index
}
const warehouseLocationRef = ref()
const confirmStorageSelection = () => {
  const node = warehouseLocationRef.value?.selectedThirdLevelNode;
  if (!node || !node.code || !node.name) {
    ElMessage.warning('请选择一个有效的三级库位');
    return; // 不关闭对话框，或根据需求决定
  }
  currentRow.value.warehouseLocationId = node.code;
  currentRow.value.warehouseLocationName = node.name;
  currentRow.value.warehouseId = node.warehouseCode;
  currentRow.value.warehouseName = node.warehouseName;

  warehouseLocationVisible.value = false;
};
let FreeGoodsRef = ref();
const handleSelectedGoods = (selected) => {
  // selected：对话框勾选的商品数据 (里面还包括了单位列表：unitList)
  // selected.forEach(goods => { const unitList = goods.unitList })
  if (selected.length > 0) {
    let unitOptionsMap = FreeGoodsRef.value.unitOptionsMap;
    //当前行后面添加选中的的商品信息
    let arr = [];
    for (let i = 0; i < selected.length; i++) {
      if (selected[i].managerType == 1) {
        showBatch.value = true; //此处应该是每次数组变化，就需要进行判断，改成watch -------------------------------未改------------------------------
      }
      let obj = {
        goodsId: selected[i].id,
        goodsCode: selected[i].code,
        goodsName: selected[i].code + ' ' + selected[i].name,
        unitId: selected[i].unit || null,
        unitName: selected[i].unitName || null,
        categoryId: selected[i].type || null,
        categoryName: selected[i].typeName || null,
        availableStock: selected[i].stock || null,
        specification: selected[i].specification || null,
        warehouseId: selected[i].warehouse || null,
        warehouseName: selected[i].warehouseName || null,
        batchNo: selected[i].type == 1 ? selected[i].batchNo : null,
        birthday: selected[i].type == 1 ? selected[i].birthday : null,
        expiration: selected[i].type == 1 ? selected[i].expiration : null,
        type: selected[i].managerType,
        quantity: 0, //默认
        unitPrice: 0.0,
        totalPrice: 0.0,
      }
      //选择商品时就展示单位列表
      obj.unitList = unitOptionsMap[obj.goodsId];
      arr[i] = obj
    }
    //当前下标往后添加选中的商品
    inboundDetailList.value.splice(currentIndex.value, 1, ...arr);
    console.log("detailList", inboundDetailList.value)
    console.log("onGoodsSelected", selected)
  }
}

const updateUnitName = (row) => {
  if (!row.unitId || !row.unitList) {
    row.unitName = null;
    return;
  }
  const selectedUnit = row.unitList.find(u => u.id === row.unitId);
  row.unitName = selectedUnit ? selectedUnit.name : null;
};

function openBatchDialog(row, index) {
  batchVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}



//这例的selected就是选中的批次列表
const onBatchSelected = (selected) => {
  if (selected.length > 0) {
    let arr = []
    for (let i = 0; i < selected.length; i++) {
      let obj = JSON.parse(JSON.stringify(currentRow.value)); //深拷贝
      obj.batchNo = selected[i].code;
      arr.push(obj);
    }
    //这里是参考精斗云中的效果，选中多个批次，则复制几份对象
    inboundDetailList.value.splice(currentIndex.value, 1, ...arr);
  }
}
const addDetailRow = (index) => {
  inboundDetailList.value.splice(index + 1, 0, {});
}
const removeDetailRow = (index) => {
  if (inboundDetailList.value.length === 1) {
    ElMessage({
      message: '至少保留一条记录',
      type: 'warning',
    })
    return;
  }
  inboundDetailList.value.splice(index, 1);
}

//  原始明细（用于修改时候的和原数据对比）
const originalOrder = ref(null), originalDetailList = ref([]);

let filteredDetailList = ref(null);
let hasZeroUnitPrice = ref(null);

const validSave = () => {
  // 过滤掉 goods 为空的明细项
  filteredDetailList.value = inboundDetailList.value.filter(item => item.goodsName);

  if (inboundOrder.value.type === '') {
    ElMessage({ message: '请选择入库单类型', type: 'warning' });
    return false;
  }
  if (!filteredDetailList.value.length) {
    ElMessage({ message: '请添加入库明细', type: 'warning' });
    return false;
  }

  hasZeroUnitPrice.value = false;

  // 先做基础字段校验，并收集 type=2 的明细
  const serialItemsByGoodsId = new Map(); // Map<goodsId, Array<{ detail, serialList }>>

  for (const detail of filteredDetailList.value) {
    // 基础校验
    if (detail.unitPrice <= 0) hasZeroUnitPrice.value = true;
    if (!detail.warehouseId) {
      ElMessage({ message: `请选择【${detail.goodsName}】的仓库`, type: 'warning' });
      return false;
    }
    if (detail.quantity <= 0) {
      ElMessage({ message: `商品【${detail.goodsName}】的数量不能为空`, type: 'warning' });
      return false;
    }
    if (detail.type == 1 && !detail.batchNo) {
      ElMessage({ message: `商品【${detail.goodsName}】的批次号不能为空`, type: 'warning' });
      return false;
    }
    if (!detail.warehouseLocationId) {
      ElMessage({ message: `请选择【${detail.goodsName}】的库位`, type: 'warning' });
      return false;
    }

    // 如果是序列号类型，准备用于后续校验
    if (detail.type == 2) {
      const serialList = detail.serialList || [];
      if (!serialList.length) {
        ElMessage({ message: `商品【${detail.goodsName}】必须填写至少一个序列号`, type: 'warning' });
        return false;
      }

      // 行内空值 & 行内重复校验（可选，提升体验）
      const currentRowSNs = new Set();
      for (const s of serialList) {
        if (!s.serialNo?.trim()) {
          ElMessage({ message: `商品【${detail.goodsName}】存在空序列号`, type: 'warning' });
          return false;
        }
        const snUpper = s.serialNo.trim().toUpperCase();
        if (currentRowSNs.has(snUpper)) {
          ElMessage({ message: `商品【${detail.goodsName}】的序列号【${snUpper}】在同一行中重复`, type: 'warning' });
          return false;
        }
        currentRowSNs.add(snUpper);
      }

      // 按 goodsId 分组
      const goodsId = detail.goodsId;
      if (!serialItemsByGoodsId.has(goodsId)) {
        serialItemsByGoodsId.set(goodsId, []);
      }
      serialItemsByGoodsId.get(goodsId).push({
        detail,
        serialList
      });
    }
  }

  // 第二阶段：按 goodsId 校验跨行序列号唯一性（大写后）
  for (const [goodsId, items] of serialItemsByGoodsId.entries()) {
    console.log("比较" + goodsId + "的serialNo");
    const globalSNSet = new Set();
    let firstGoodsName = '';

    for (const { detail, serialList } of items) {
      if (!firstGoodsName) firstGoodsName = detail.goodsName;

      for (const s of serialList) {
        const snUpper = s.serialNo.trim().toUpperCase();

        if (globalSNSet.has(snUpper)) {
          ElMessage({
            message: `商品【${firstGoodsName}】的序列号【${snUpper}】在多个明细行中重复，请检查！`,
            type: 'warning'
          });
          return false;
        }
        globalSNSet.add(snUpper); //比较后面的
      }
    }
  }

  return true;
};
const save = () => {
  //根据code判断此处是修改还是新增
  if (props.code || inboundOrder.value.code) {
    //修改 - 对比原数组。分别获得 新增、修改、删除三个数组。
    if (validSave()) modify();
  }
  else {//新增
    if (validSave()) {
      if (hasZeroUnitPrice.value) {
        ElMessageBox.confirm(
          '存在入库单价为0的商品,是否仍要继续?',
          '警告',
          {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning',
            center: true,
          }
        )
          .then(() => {
            add(filteredDetailList.value);
          })
          .catch(() => {
            console.log("用户取消保存");
          })
      } else {
        add(filteredDetailList.value);
      }
    }


  }
}


function modify() {
  //1.map根据id快速获取原数组
  const originalMap = new Map(
    originalDetailList.value.map(item => [item.id, item])
  );
  //2.遍历当前列表：找新增 & 修改
  let addArr = [], delArr = [], modArr = [];
  inboundDetailList.value.forEach(i => {
    if (!i.id) {
      addArr.push(i); //新增
    } else {
      //判断修改
      if (hasModifiedDetail(i, originalMap.get(i.id))) {
        modArr.push(i);
      }
      //map数据比较过就删除， map中数据 - 当前明细 = 已删除数据
      originalMap.delete(i.id);
    }
  })
  //3.剩下的 originalMap 中的 id 就是被删除的
  for (const id of originalMap.keys()) {
    delArr.push(id);
  }
  //提交修改
  axios({
    url: `/xyy/inbound/modify`,
    method: 'post',
    data: {
      orderModified: hasModifiedOrder(originalOrder.value, inboundOrder.value),
      addArr: addArr,
      modArr: modArr,
      delArr: delArr,
      inboundOrder: { ...inboundOrder.value },
    }
  }).then(rs => {
    if (rs.data.code == 5200) {
      ElMessage({ message: "修改入库单成功", type: 'success', });
      router.push({ name: 'inbound' });
    }
  })
}

const saveAndSubmit = () => {
  //保存
  inboundOrder.value.status = 2;
  save();
}

//判断当前入库明细是否修改
function hasModifiedDetail(current, original) {
  // 先比较基础字段
  const basicFields = ["unitId", "warehouseId", "batchNo", "warehouseLocationId", "quantity", "unitPrice"];
  const basicModified = basicFields.some(field => current[field] != original[field]);
  // 如果基础字段已修改，直接返回 true
  if (basicModified) return true;
  // 如果是序列号管理类型（type == 2），再比较 serialList
  if (current.type == 2) {
    return !serialListsEqual(current.serialList, original.serialList);
  }
  // 其他类型（如批次）无需比较 serialList
  return false;
}
function hasModifiedOrder(current, original) {
  const fields = ["createdTime", "type", "sourceOrderCode", "remark", "status"]
  return fields.some(field => current[field] != original[field]);
}

// 深度比较两个序列号列表是否完全相同（顺序无关）
function serialListsEqual(list1, list2) {
  if (!list1 && !list2) return true;
  if (!list1 || !list2) return false;
  if (list1.length !== list2.length) return false;

  // 转为字符串集合便于比较（保证 serialNo 唯一）
  const set1 = new Set(list1.map(s => `${s.serialNo}|${s.remark || ''}`));
  const set2 = new Set(list2.map(s => `${s.serialNo}|${s.remark || ''}`));

  if (set1.size !== set2.size) return false;

  for (let item of set1) {
    if (!set2.has(item)) return false;
  }
  return true;
}



const add = (filteredDetailList) => {
  axios({
    url: '/xyy/inbound/create',
    method: 'post',
    data: {
      inboundOrder: inboundOrder.value,
      // 过滤后的明细列表
      inboundOrderItemList: filteredDetailList
    }
  }).then(rs => {
    console.log(rs);
    if (rs.data.code == 5200) {
      ElMessage({ message: "新增入库单成功", type: 'success', });
      router.push({ name: 'inbound' });
    } else {
      ElMessage({ message: "新增入库单失败", type: 'danger', });
    }


  })
}

// 审核 - 根据入库表id进行审核
const auditor = () => {
  axios({
    url: `/xyy/inbound/auditor`,
    method: 'post',
    data: {
      inboundOrder: inboundOrder.value,
      inboundOrderItemList: inboundDetailList.value,
    }
  }).then(rs => {
    if (rs.data.code == 5200) {
      ElMessage({ message: "审核成功", type: 'success', });
      router.push({ name: 'inbound' })
      return;
    }
    ElMessage({ message: "审核失败: " + rs.data.msg, type: 'danger', });
  })
}

//进入修改操作的数据初始化
function init() {
  axios({
    url: '/xyy/inbound/get/' + props.id,
    method: 'post',
  }).then(rs => {
    if (rs.data.code == 5200 && rs.data.inboundOrderRequest) {
      //初始化时也要加载unitList
      inboundOrder.value = rs.data.inboundOrderRequest.inboundOrder;
      inboundDetailList.value = rs.data.inboundOrderRequest.inboundOrderItemList;

      // 延迟赋值 unitList，等 FreeGoodsRef 准备好
      assignUnitList();
    }
  })
}


const assignUnitList = () => {
  const map = FreeGoodsRef.value?.unitOptionsMap;

  if (!map) {
    setTimeout(assignUnitList, 100);
    return;
  }

  // 检查是否所有商品的 unitList 都已加载
  const allLoaded = inboundDetailList.value.every(i => {
    const goodsId = String(i.goodsId).trim();
    return map[goodsId] !== undefined;
  });

  if (!allLoaded) {
    setTimeout(assignUnitList, 100);
    return;
  }

  // ✅ 开始赋值 unitList 和 unitId
  inboundDetailList.value.forEach(i => {
    const goodsId = String(i.goodsId).trim();
    const unitList = map[goodsId] || [];
    i.unitList = unitList;

    // 如果已经有 unitId（比如后端返回了），就保留
    if (i.unitId != null) {
      return;
    }

    // 否则根据 unitList 自动设置默认 unitId
    if (unitList.length === 0) {
      i.unitId = null;
      return;
    }

    // 尝试找 conversion === 1 的单位（主单位）
    const baseUnit = unitList.find(u => u.conversion === 1);
    if (baseUnit) {
      i.unitId = baseUnit.id;
    } else {
      // 否则选第一个
      i.unitId = unitList[0].id;
    }
  });

  // 深拷贝初始状态
  originalDetailList.value = JSON.parse(JSON.stringify(inboundDetailList.value));
  originalOrder.value = JSON.parse(JSON.stringify(inboundOrder.value));
};


// 弹窗控制
const serialVisible = ref(false)

function handleQuantityClick(row, index) {
  currentRow.value = row;
  currentIndex.value = index
  if (row.type === 2) {
    serialVisible.value = true;
  }
}

const showSelectGoods = ref(false)
function openGoodsDialog(row, index) {
  showSelectGoods.value = true
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}
let AddSerialNumberRef = ref();
const confirmSerialSelection = () => {
  const validList = AddSerialNumberRef.value?.getValidSerialList();
  if (validList && validList.length > 0) {
    // 直接保存为数组
    validList.forEach(i => i.type = 0); //type = 0 入库
    currentRow.value.serialList = [...validList]; // 深拷贝
    currentRow.value.quantity = validList.length;

  } else {
    ElMessage.warning("未选择任何有效序列号");
  }
  serialVisible.value = false; // 关闭对话框
}




onMounted(() => {
  //如果是修改，获取到入库单和入库明细
  if (props.id) {
    init();
  } else {
    inboundDetailList.value = [{
      quantity: 0,
      unitPrice: 0,
      totalPrice: 0,
    }]
    inboundOrder.value.createdTime = formatDate(new Date());
    datePickerValue.value = inboundOrder.value.createdTime.substring(0, 10)
  }
})

</script>

<style></style>